#!/bin/bash

# 配置参数
SERVER_IP=$3
SERVER_URL="http://"\"$SERVER_IP"\":5000/report"  # 替换为您的服务器IP和端口
DEVICE_ID="获取ip的车"                      # 设备唯一ID
DEVICE_NAME="agv车"                      # 设备名称

# 检查参数
if [ -z "$1" -o -z "$2" ]; then
    exit 10
fi

# 清理现有无线连接
nmcli -t -f NAME,UUID,TYPE,DEVICE c | awk -F: '/:802-11-wireless:/{print "echo 123 | sudo -S nmcli c del " $2}' | bash
sleep 1

# 连接新Wi-Fi网络
echo 123 | sudo -S nmcli --wait 20 device wifi connect "$1" password "$2" ifname wlan0

# 等待网络连接
sleep 5

# 获取新IP
NEW_IP=$(ip -4 addr show wlan0 | grep inet | awk '{print $2}' | cut -d'/' -f1 | head -n1)

# 如果获取到IP，则上报到服务器
if [ -n "$NEW_IP" ]; then
    # 上报IP到服务器
    curl -X POST -H "Content-Type: application/json" -d "{
        \"device_id\": \"$DEVICE_ID\",
        \"device_name\": \"$DEVICE_NAME\",
        \"ip\": \"$NEW_IP\"
    }" $SERVER_URL > /dev/null 2>&1
    
fi

# 检查网络状态
state=$(cat /sys/class/net/wlan0/operstate)
if [ "$state" == "up" ]; then
    exit 0
else
    exit -1
fi